package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bac.BacDrugTestResultMapper;
import com.ysd.lis.mapper.bac.BacObserResultMapper;
import com.ysd.lis.mapper.bac.BacStainingResultMapper;
import com.ysd.lis.mapper.bac.BacTestResultMapper;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.pub.PubReportRulesMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethExtParamMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethodMapper;
import com.ysd.lis.request.LabMainInfoMerge;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.*;
import com.ysd.lis.util.lab.CalcItemFormulaReplcae;
import com.ysd.util.SortMappers;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class LabMaininfoServiceExtendImpl extends ServiceImpl<LabItemDictMapper, LabItemDict> {
    private static final Logger logger = LoggerFactory.getLogger(LabMaininfoServiceExtendImpl.class);

    @Autowired
    LabReqMainMapper labReqMainMapper;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    LabRptresultMapper labRptresultMapper;

    @Autowired
    LabRptresultImageMapper labRptresultImageMapper;

    @Autowired
    LabRptresultImageService labRptresultImageService;

    @Autowired
    LabRptmainMapper labRptmainMapper;

    @Autowired
    LabRptdetailMapper labRptdetailMapper;

    @Autowired
    PubReportRulesMapper reportRulesMapper;

    @Autowired
    LabRulesVsItemdictMapper rulesVsItemdictMapper;

    @Autowired
    LabReqStateService labReqStateService;

    @Autowired
    LabMainStateService labMainStateService;

    @Autowired
    LabRptGroupMapper labRptGroupMapper;

    @Autowired
    LabRptresultService labRptresultService;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    SysParamValueService sysParamValueService;

    @Autowired
    LabTemplateService labTemplateService;

    @Autowired
    LabResultAmendmentMapper labResultAmendmentMapper;

    @Autowired
    LabResultAmendmentService labResultAmendmentService;

    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    BacObserResultMapper bacObserResultMapper;
    @Autowired
    LabRptdetailBacService labRptdetailBacService;
    @Autowired
    LabRptdetailStainingService labRptdetailStainingService;
    @Autowired
    LabRptdetailDrugService labRptdetailDrugService;
    @Autowired
    LabRptdetailObserService labRptdetailObserService;
    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    SysInterfaceMethodMapper sysInterfaceMethodMapper;

    @Autowired
    SysInterfaceMethExtParamMapper sysInterfaceMethExtParamMapper;

    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    LabReqdetailDelService labReqdetailDelService;
    @Autowired
    LabReqdetailMapper labReqdetailMapper;
    @Autowired
    LabRptVsBarcodeMapper labRptVsBarcodeMapper;
    @Autowired
    RedisSysParamHelper redisSysParamHelper;

    @Value("${mybatis-plus.configuration.page-type}")
    private String pageType;

    /**
     * 初步审核
     */
    public static final String PRELIMINARY_REVIEW = "1";
    /**
     * 取消初步审核
     */
    public static final String CANCEL_PRELIMINARY_REVIEW = "2";
    /**
     * 审核
     */
    public static final String REVIEW = "3";

    /**
     * 标本合并
     *
     * @param input 合并参数
     */
    public Result mergeTestList(LabMainInfoMerge input) {
        /*待合并的检验记录*/
        List<String> aimCode = GetAimCode(input.getSourceSampleNo());
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getSourceRptGroupId());

        Timestamp startTime = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);
        queryWrapper.in(!aimCode.isEmpty(), LabMaininfo::getSampleNo, aimCode);
        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

        sortLabMainInfo(list);


        Map<String, String> rangeCode = GetRangeCode(input.getSourceSampleNo());

        List<Predicate<LabMaininfo>> dynamicPredicates = new ArrayList<>();

        for (Map.Entry<String, String> itm : rangeCode.entrySet()) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getKey()) && p.getSeqNo() <= replaceLetter(itm.getValue()));
        }

        for (String itm : aimCode) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm) && p.getSeqNo() <= replaceLetter(itm));
        }

        List<LabMaininfo> list1 = list.stream().filter(t -> dynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.fail("没有要合并的数据");
        }

        /*待合并的结果数据、文件数据*/
        List<String> sampleNos = list1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
        LambdaQueryWrapper<LabRptresult> queryRptresultWrapper = new LambdaQueryWrapper<>();
        queryRptresultWrapper.eq(LabRptresult::getDelFlag, 0);
        queryRptresultWrapper.in(!sampleNos.isEmpty(), LabRptresult::getSampleNo, sampleNos);
        queryRptresultWrapper.eq(LabRptresult::getRptGroup, input.getSourceRptGroupId());

        Timestamp startTime1 = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime1 = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 23:59:59");
        queryRptresultWrapper.ge(LabRptresult::getSampleda, startTime1);
        queryRptresultWrapper.le(LabRptresult::getSampleda, endTime1);


        if (!input.getItemDictCodes().isEmpty()) {
            queryRptresultWrapper.in(LabRptresult::getItemNo, input.getItemDictCodes());
        }
        List<LabRptresult> rptResultListSource = labRptresultMapper.selectList(queryRptresultWrapper);

        LambdaQueryWrapper<LabRptresultImage> queryRptresultImageWrapper = new LambdaQueryWrapper<>();
        queryRptresultImageWrapper.eq(LabRptresultImage::getDelFlag, 0);
        queryRptresultImageWrapper.in(!sampleNos.isEmpty(), LabRptresultImage::getSampleNo, sampleNos);
        queryRptresultImageWrapper.ge(LabRptresultImage::getSampleda, startTime1);
        queryRptresultImageWrapper.le(LabRptresultImage::getSampleda, endTime1);
        queryRptresultImageWrapper.eq(LabRptresultImage::getRptGroup, input.getSourceRptGroupId());
        List<LabRptresultImage> rptResultImageListSource = labRptresultImageMapper.selectList(queryRptresultImageWrapper);



        /*目标数据*/
        List<String> tAimCode = GetAimCode(input.getTargetSampleNo());
        LambdaQueryWrapper<LabMaininfo> tQueryWrapper = new LambdaQueryWrapper<>();
        tQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        tQueryWrapper.eq(LabMaininfo::getRptGroup, input.getTargetRptGroupId());

        Timestamp tStartTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 00:00:00");
        Timestamp tEndTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 23:59:59");
        tQueryWrapper.ge(LabMaininfo::getSampleda, tStartTime);
        tQueryWrapper.le(LabMaininfo::getSampleda, tEndTime);
        tQueryWrapper.in(!tAimCode.isEmpty(), LabMaininfo::getSampleNo, tAimCode);
        List<LabMaininfo> tList = labMaininfoMapper.selectList(tQueryWrapper);

        sortLabMainInfo(tList);

        Map<String, String> tRangeCode = GetRangeCode(input.getTargetSampleNo());

        List<Predicate<LabMaininfo>> tDynamicPredicates = new ArrayList<>();

        for (Map.Entry<String, String> itm : tRangeCode.entrySet()) {
            tDynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getKey()) && p.getSeqNo() <= replaceLetter(itm.getValue()));
        }

        for (String itm : tAimCode) {
            tDynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm) && p.getSeqNo() <= replaceLetter(itm));
        }

        List<LabMaininfo> tList1 = tList.stream().filter(t -> tDynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        /*是否一对多合并*/
        boolean OneToMany = false;

        List<String> SourceCodes = getCodeRangeList(input.getSourceSampleNo());//list1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());

        List<String> TargetCodes = null;//

        //非自动合并
        if (!BeanUtil.isEmpty(input.getAutoMerge()) && input.getAutoMerge() != 1) {
            TargetCodes = getCodeRangeList(input.getTargetSampleNo());//tList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());

            if (TargetCodes.isEmpty()) {
                return Result.fail("请选择合并后标本号范围");
            }
        } else {
            TargetCodes = new ArrayList<>();
        }

        //Source count = 1 时，为一对多模式//严格判断
        if (SourceCodes.toArray().length == 1 && TargetCodes.toArray().length > 1) {
            OneToMany = true;
            //1对多时,不能合并Wl
            input.setMergePatInfo(0);
        }

        //校验标本号范围是否一致
        if (!BeanUtil.isEmpty(input.getAutoMerge()) && !OneToMany && SourceCodes.size() != TargetCodes.size()) {
            return Result.fail("合并前标本号范围与合并后标本号范围不一致!");
        }

        if (!BeanUtil.isEmpty(input.getAutoMerge()) && input.getAutoMerge().equals(1)) {
            /*查询源病人信息*/
            List<String> patNos = list1.stream().map(LabMaininfo::getPatNo).collect(Collectors.toList());
            List<String> patNas = list1.stream().map(LabMaininfo::getPatNa).collect(Collectors.toList());

            /*查询目标病人信息*/
            tQueryWrapper = new LambdaQueryWrapper<>();
            tQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
            tQueryWrapper.eq(LabMaininfo::getRptGroup, input.getTargetRptGroupId());

            tStartTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 00:00:00");
            tEndTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 23:59:59");
            tQueryWrapper.ge(LabMaininfo::getSampleda, tStartTime);
            tQueryWrapper.le(LabMaininfo::getSampleda, tEndTime);
            tQueryWrapper.in(LabMaininfo::getPatNo, patNos);
            tQueryWrapper.in(LabMaininfo::getPatNa, patNas);
            tList1 = labMaininfoMapper.selectList(tQueryWrapper);
            sortLabMainInfo(tList1);

            if (tList1.isEmpty()) {
                return Result.fail("未找到合并后病人信息");
            }
            //重新组织TargetCodes
            TargetCodes = new ArrayList<>();//tList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());

            for (LabMaininfo m : list1) {
                if (BeanUtil.isEmpty(m) || BeanUtil.isEmpty(m.getSampleNo()) || BeanUtil.isEmpty(m.getPatNo()) || BeanUtil.isEmpty(m.getPatNa())) {
                    continue;
                }
                int i = SourceCodes.indexOf(m.getSampleNo());
                List<LabMaininfo> tPats = tList.stream().filter(p -> p.getPatNo().equals(m.getPatNo()) && p.getPatNa().equals(m.getPatNa())).collect(Collectors.toList());

                if (tPats.isEmpty()) {
                    continue;
                }
                if (tPats.size() > 1) {
                    return Result.fail("合并前标本号" + m.getSampleNo() + "对应的病人信息重复,无法自动合并!");
                }
                if (i <= TargetCodes.toArray().length - 1 && BeanUtil.isEmpty(TargetCodes.get(i))) {
                    TargetCodes.set(i, tPats.get(0).getSampleNo());
                }
            }
        }

        /*准备待合并的目标检验结果*/
        List<String> tSampleNos = tList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
        LambdaQueryWrapper<LabRptresult> tResultQueryWrapper = new LambdaQueryWrapper<>();
        tResultQueryWrapper.eq(LabRptresult::getDelFlag, 0);
        tResultQueryWrapper.eq(LabRptresult::getRptGroup, input.getTargetRptGroupId());
        tResultQueryWrapper.ge(LabRptresult::getSampleda, tStartTime);
        tResultQueryWrapper.le(LabRptresult::getSampleda, tEndTime);
        tResultQueryWrapper.in(!tSampleNos.isEmpty(), LabRptresult::getSampleNo, tSampleNos);
        if (!input.getItemDictCodes().isEmpty()) {
            tResultQueryWrapper.in(LabRptresult::getItemNo, input.getItemDictCodes());
        }
        if (tSampleNos.isEmpty()) {
            tResultQueryWrapper.eq(LabRptresult::getMaininfoId, "!@#QWE!@#");
        }
        List<LabRptresult> tResultList = labRptresultMapper.selectList(tResultQueryWrapper);

        /*准备待合并的目标检验结果文件*/
        LambdaQueryWrapper<LabRptresultImage> tResultImageQueryWrapper = new LambdaQueryWrapper<>();
        tResultImageQueryWrapper.eq(LabRptresultImage::getDelFlag, 0);
        tResultImageQueryWrapper.eq(LabRptresultImage::getRptGroup, input.getTargetRptGroupId());
        tResultImageQueryWrapper.ge(LabRptresultImage::getSampleda, tStartTime);
        tResultImageQueryWrapper.le(LabRptresultImage::getSampleda, tEndTime);
        tResultImageQueryWrapper.in(!tSampleNos.isEmpty(), LabRptresultImage::getSampleNo, tSampleNos);
        if (tSampleNos.isEmpty()) {
            tResultImageQueryWrapper.eq(LabRptresultImage::getMaininfoId, "!@#QWE!@#");
        }
        List<LabRptresultImage> tResultImageList = labRptresultImageMapper.selectList(tResultImageQueryWrapper);


        /*验证是否够锁定、初审、审核*/
        List<LabMaininfo> validateList = tList1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());
        if (!validateList.isEmpty()) {
            return Result.fail("以下标本已锁定,无法合并!" + validateList.stream().map(LabMaininfo::getSampleNo).collect(Collectors.joining(",")));
        }
        List<LabMaininfo> validateList1 = tList1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().equals(new BigDecimal(1)) || p.getIsChk().equals(new BigDecimal(2)))).collect(Collectors.toList());
        if (!validateList1.isEmpty()) {
            return Result.fail("以下标本已初审或已审核,无法合并!" + validateList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.joining(",")));
        }


        /*准备合并数据*/
        List<LabMaininfo> newMainInfoList = new ArrayList<>();
        List<LabRptresult> newRptResultList = new ArrayList<>();
        List<LabRptresultImage> newRptResultImageList = new ArrayList<>();

        List<LabMaininfo> overwriteMainInfoList = new ArrayList<>();
        List<LabRptresult> overwriteRptResultList = new ArrayList<>();
        List<LabRptresultImage> overwriteRptResultImageList = new ArrayList<>();

        List<LabMaininfo> deleteTMainInfoList = new ArrayList<>();
        List<LabRptresult> deleteTRptResultList = new ArrayList<>();
        List<LabRptresultImage> deleteTRptResultImageList = new ArrayList<>();

        int oneToManyCount = 0;
        for (int i = 0; i < list1.size(); i++) {
            LabMaininfo sw;
            int sIndex = 0;
            if (OneToMany) {
                if (oneToManyCount >= TargetCodes.size()) {
                    break;
                }
                i = 0;
                sw = list1.get(0);
                sIndex = oneToManyCount;

                oneToManyCount += 1;
            } else {
                sw = list1.get(i);
                String sSampleNo = sw.getSampleNo();
                sIndex = SourceCodes.indexOf(sSampleNo);
            }
            //得到目标标本号
            String tCode = TargetCodes.get(sIndex);

            //自动合并合并未找到目标Code时，不继续
            if (!BeanUtil.isEmpty(input.getAutoMerge()) && input.getAutoMerge().equals(1) && BeanUtil.isEmpty(tCode)) {
                continue;
            }

            List<LabMaininfo> tmis = tList1.stream().filter(p -> p.getSampleNo().equals(tCode)).collect(Collectors.toList());
            LabMaininfo tmiFirst = tmis.isEmpty() ? null : tmis.get(0);

            //Timestamp finalTStartTime = tStartTime;
            //Timestamp finalTEndTime = tEndTime;
            //List<LabRptresult> rptresults = tResultList.stream().filter(p -> p.getRptGroup().equals(sw.getRptGroup()) && p.getSampleda().after(finalTStartTime) && p.getSampleda().before(finalTEndTime) && p.getSampleNo().equals(sw.getSampleNo())).collect(Collectors.toList());//p.getMaininfoId().equals(sw.getId())
            //Timestamp finalTStartTime1 = tStartTime;
            //List<LabRptresultImage> rptresultimages = tResultImageList.stream().filter(p -> p.getRptGroup().equals(sw.getRptGroup()) && p.getSampleda().after(finalTStartTime1) && p.getSampleda().before(finalTEndTime) && p.getSampleNo().equals(sw.getSampleNo())).collect(Collectors.toList());//p.getMaininfoId().equals(sw.getId())

            LabMaininfo _miEntry = new LabMaininfo();
            if (!BeanUtil.isEmpty(tmiFirst)) {
                BeanUtil.copyProperties(tmiFirst, _miEntry);
                /*1：覆盖，0取消*/
                if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(1)) {
                    BeanUtil.copyProperties(sw, _miEntry, "id");
                    _miEntry.setSampleda(tmiFirst.getSampleda());
                    _miEntry.setRptGroup(tmiFirst.getRptGroup());
                    _miEntry.setSampleNo(tmiFirst.getSampleNo());
                    _miEntry.setCreateTime(tmiFirst.getCreateTime());
                }
                _miEntry.setReqNo(sw.getReqNo());
                _miEntry.setSampleType(sw.getSampleType());
                _miEntry.setQuantity(sw.getQuantity());
                _miEntry.setIsChk(new BigDecimal(0));
                _miEntry.setTestDoctor("");
                _miEntry.setChkDoctor("");
                _miEntry.setChkTime(null);
                _miEntry.setIsPrint(0);
                _miEntry.setPrintDoctor("");
                _miEntry.setPrintTime(null);
                _miEntry.setPrintCount(new BigDecimal(0));
                _miEntry.setIsLock(0);
                _miEntry.setIsAutoPrint(0);
                _miEntry.setAutoPrintTime(null);
                if (BeanUtil.isEmpty(input.getMergePatInfo()) || !input.getMergePatInfo().equals(1)) {
                    /*不合并病人信息*/
                    _miEntry.setReqNo("");
                    _miEntry.setPatType("");
                    _miEntry.setPatNa("");
                    _miEntry.setPatNo("");
                    _miEntry.setPatPyName("");
                    _miEntry.setSex("");
                    _miEntry.setAge(null);
                    _miEntry.setAgeUnit("");
                    _miEntry.setSecAge(null);
                    _miEntry.setSecAgeUnit("");
                    _miEntry.setIdNo(null);
                }
                /*合并检验医师*/
                if (!BeanUtil.isEmpty(input.getMergeTestDoctor()) && input.getMergeTestDoctor().equals(1)) {
                    _miEntry.setChkDoctor(sw.getChkDoctor());
                    _miEntry.setTestDoctor(sw.getTestDoctor());
                }
                overwriteMainInfoList.add(_miEntry);
            } else {
                /*生成新数据*/
                BeanUtil.copyProperties(sw, _miEntry, "id");
                _miEntry.setSampleda(Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 00:00:00"));
                _miEntry.setRptGroup(input.getTargetRptGroupId());
                _miEntry.setSampleNo(tCode);
                _miEntry.setIsChk(new BigDecimal(0));
                _miEntry.setTestDoctor(null);
                _miEntry.setChkDoctor(null);
                _miEntry.setChkTime(null);
                _miEntry.setIsPrint(0);
                _miEntry.setPrintDoctor(null);
                _miEntry.setPrintTime(null);
                _miEntry.setPrintCount(new BigDecimal(0));
                _miEntry.setIsLock(0);
                _miEntry.setIsAutoPrint(0);
                _miEntry.setAutoPrintTime(null);
                if (BeanUtil.isEmpty(input.getMergePatInfo()) || !input.getMergePatInfo().equals(1)) {
                    /*不合并病人信息*/
                    _miEntry.setReqNo(null);
                    _miEntry.setPatType(null);
                    _miEntry.setPatNa(null);
                    _miEntry.setPatNo(null);
                    _miEntry.setPatPyName(null);
                    _miEntry.setSex(null);
                    _miEntry.setAge(null);
                    _miEntry.setAgeUnit(null);
                    _miEntry.setSecAge(null);
                    _miEntry.setSecAgeUnit(null);
                    _miEntry.setIdNo(null);
                }

                if (!BeanUtil.isEmpty(input.getMergeTestDoctor()) && input.getMergeTestDoctor().equals(1)) {
                    _miEntry.setChkDoctor(sw.getChkDoctor());
                    _miEntry.setTestDoctor(sw.getTestDoctor());
                }
                newMainInfoList.add(_miEntry);
            }

            /*待合并结果处理*/
            List<LabRptresult> _srptrList = rptResultListSource.stream().filter(p -> p.getSampleNo().equals(sw.getSampleNo()) && p.getRptGroup().equals(sw.getRptGroup())).collect(Collectors.toList());//p.getMaininfoId().equals(sw.getId())
            for (LabRptresult srptritm : _srptrList) {
                LabRptresult _rptEntry = new LabRptresult();
                LabRptresult _rptEntryTemp = new LabRptresult();
                /*按项目代号合并 0否  1是*/
                if (!BeanUtil.isEmpty(input.getMergeByItemNo()) && input.getMergeByItemNo().equals(1)) {
                    String itemNo = srptritm.getItemNo();

                    List<LabRptresult> _rptResultAimItems = tResultList.stream().filter(p -> p.getItemNo().equals(itemNo) && p.getSampleNo().equals(tCode)).collect(Collectors.toList());
                    if (!_rptResultAimItems.isEmpty()) {
                        BeanUtil.copyProperties(_rptResultAimItems.get(0), _rptEntry);
                    }

                    BeanUtil.copyProperties(srptritm, _rptEntryTemp, "id");
                } else {
                    String itemNo = srptritm.getItemNo();

                    List<LabRptresult> _rptResultAimItems = tResultList.stream().filter(p -> p.getItemNo().equals(itemNo) && p.getSampleNo().equals(tCode)).collect(Collectors.toList());
                    if (!_rptResultAimItems.isEmpty()) {
                        BeanUtil.copyProperties(_rptResultAimItems.get(0), _rptEntry);
                    }

                    BeanUtil.copyProperties(srptritm, _rptEntryTemp, "id");
                }

                if (StringUtils.isBlank(_miEntry.getId())) {
                    // 获取UUID的前19位作为ASSIGN_ID
                    String assignId = IdUtil.getSnowflake().nextId() + "";
                    _miEntry.setId(assignId);
                }

                _rptEntryTemp.setMaininfoId(_miEntry.getId());
                _rptEntryTemp.setSampleda(_miEntry.getSampleda());
                _rptEntryTemp.setRptGroup(_miEntry.getRptGroup());
                _rptEntryTemp.setSampleNo(_miEntry.getSampleNo());

                if (BeanUtil.isEmpty(_rptEntry) || StringUtils.isBlank(_rptEntry.getId())) {
                    newRptResultList.add(_rptEntryTemp);
                } else {
                    /*如果存在就取消*/
                    if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(0)) {
                        continue;
                    }

                    /*单个项目合并时 不删除目标中原有的检验项目结果*/
                    if (ToolsUtils.isNotEmpty(input.getIsOneItemDict()) && input.getIsOneItemDict().equals(1)) {
                        //
                    } else {
                        _rptEntry.setDelFlag(1);
                        deleteTRptResultList.add(_rptEntry);//已经存在的删除
                    }
                    newRptResultList.add(_rptEntryTemp);//添加一条新的
                }
            }

            /*待合并结果文件处理*/
            List<LabRptresultImage> _srptrimageList = rptResultImageListSource.stream().filter(p -> p.getSampleNo().equals(sw.getSampleNo()) && p.getRptGroup().equals(sw.getRptGroup())).collect(Collectors.toList());
            for (LabRptresultImage swrf : _srptrimageList) {
                List<LabRptresultImage> _entries = tResultImageList.stream().filter(p -> p.getImageName().equals(swrf.getImageName())).collect(Collectors.toList());

                LabRptresultImage _entry = new LabRptresultImage();
                BeanUtil.copyProperties(swrf, _entry, "id");
                if (StringUtils.isBlank(_miEntry.getId())) {
                    String assignId = IdUtil.getSnowflake().nextId() + "";
                    _miEntry.setId(assignId);
                }
                _entry.setMaininfoId(_miEntry.getId());
                _entry.setSampleda(_miEntry.getSampleda());
                _entry.setRptGroup(_miEntry.getRptGroup());
                _entry.setSampleNo(_miEntry.getSampleNo());
                if (_entries.isEmpty()) {
                    newRptResultImageList.add(_entry);
                } else {
                    LabRptresultImage delEntry = _entries.get(0);
                    delEntry.setDelFlag(1);

                    /*已有该图片情况下*/
                    /*如果存在就取消*/
                    if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(0)) {
                        continue;
                    }
                    /*复制*/
                    /*移动*/
                    /*如果存在就覆盖*/
                    deleteTRptResultImageList.add(delEntry);
                    newRptResultImageList.add(_entry);
                }
            }

            if (OneToMany) {
                i = -1;
            }

        }
        //保存数据
        //插入新生成的数据
        if (!newMainInfoList.isEmpty()) {
            boolean ires1 = labMaininfoService.saveBatch(newMainInfoList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!overwriteMainInfoList.isEmpty() && !BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(1)) {
            boolean ires11 = labMaininfoService.updateBatchById(overwriteMainInfoList);
            if (!ires11) {
                return Result.fail("合并更新检验记录失败,请联系管理员");
            }
        }

        if (!newRptResultList.isEmpty() && input.getIsAllItemDict() != null && input.getIsAllItemDict().equals(1)) {
            boolean ires2 = labRptresultService.saveBatch(newRptResultList);
            if (!ires2) {
                return Result.fail("合并结果失败,请联系管理员");
            }
        }

        /*按单个项目合并*/
        if (input.getIsOneItemDict() == 1 && StringUtils.isNotEmpty(input.getItemNo())) {
            Optional<LabRptresult> first = newRptResultList.stream().filter(p -> p.getItemNo().equals(input.getItemNo())).findFirst();
            if (first.isPresent()) {
                LabRptresult labRptresult = first.get();
                boolean save = labRptresultService.save(labRptresult);
                if (!save) {
                    return Result.fail("合并结果失败,请联系管理员");
                }
            }
        }

        if (!BeanUtil.isEmpty(input.getMergeFile()) && input.getMergeFile().equals(1) && !newRptResultImageList.isEmpty()) {
            boolean ires3 = labRptresultImageService.saveBatch(newRptResultImageList);
            if (!ires3) {
                return Result.fail("合并文件失败,请联系管理员");
            }
        }

        if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(1)) {
            if (!deleteTRptResultList.isEmpty()) {
                int ires4 = labRptresultMapper.deleteBatchIds(deleteTRptResultList.stream().map(LabRptresult::getId).collect(Collectors.toList()));
                if (ires4 <= 0) {
                    return Result.fail("合并删除结果失败,请联系管理员");
                }
            }

            if (!BeanUtil.isEmpty(input.getMergeFile()) && input.getMergeFile().equals(1) && !deleteTRptResultImageList.isEmpty()) {
                int ires5 = labRptresultImageMapper.deleteBatchIds(deleteTRptResultImageList.stream().map(LabRptresultImage::getId).collect(Collectors.toList()));
                if (ires5 <= 0) {
                    return Result.fail("合并删除文件失败,请联系管理员");
                }
            }
        }

        //非复制模式，移动数据。
        //需要删除source数据
        if (!BeanUtil.isEmpty(input.getCopy()) && !input.getCopy().equals(1)) {
            if (!BeanUtil.isEmpty(input.getMergePatInfo()) && input.getMergePatInfo().equals(1)) {
                for (LabMaininfo m : list1) {
                    m.setDelFlag(1);
                }
                if (!list1.isEmpty()) {
                    int ires8 = labMaininfoMapper.deleteBatchIds(list1.stream().map(LabMaininfo::getId).collect(Collectors.toList()));
                    if (ires8 <= 0) {
                        return Result.fail("合并删除检验记录失败,请联系管理员");
                    }
                }
            }

            for (LabRptresult m : rptResultListSource) {
                m.setDelFlag(1);
            }

            if (!rptResultListSource.isEmpty()) {
                /*按单个项目移动，只删除这一个项目*/
                if (ToolsUtils.isNotEmpty(input.getIsOneItemDict()) && input.getIsOneItemDict().equals(1)) {
                    List<LabRptresult> oneIds = rptResultListSource.stream().filter(p -> p.getItemNo().equals(input.getItemNo())).collect(Collectors.toList());

                    /*如果存在就取消，则不删除*/
                    if (!oneIds.isEmpty() && (ToolsUtils.isNotEmpty(input.getOverwrite()) && input.getOverwrite().equals(0))) {
                        int ires9 = labRptresultMapper.deleteBatchIds(oneIds.stream().map(LabRptresult::getId).collect(Collectors.toList()));
                        if (ires9 <= 0) {
                            return Result.fail("合并删除检验结果失败,请联系管理员");
                        }
                    }
                } else {
                    int ires9 = labRptresultMapper.deleteBatchIds(rptResultListSource.stream().map(LabRptresult::getId).collect(Collectors.toList()));
                    if (ires9 <= 0) {
                        return Result.fail("合并删除检验结果失败,请联系管理员");
                    }
                }
            }

            for (LabRptresultImage m : rptResultImageListSource) {
                m.setDelFlag(1);
            }

            if (!rptResultImageListSource.isEmpty()) {
                int ires10 = labRptresultImageMapper.deleteBatchIds(rptResultImageListSource.stream().map(LabRptresultImage::getId).collect(Collectors.toList()));
                if (ires10 <= 0) {
                    return Result.fail("合并删除检验文件失败,请联系管理员");
                }
            }
        }

        return Result.succ(1, "合并成功", null);
    }

    public Result mergeTestListNew(LabMainInfoMerge input) {
        /*待合并的检验记录*/
        List<String> aimCode = GetAimCode(input.getSourceSampleNo());
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getSourceRptGroupId());

        Timestamp startTime = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);
        queryWrapper.in(!aimCode.isEmpty(), LabMaininfo::getSampleNo, aimCode);
        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

        sortLabMainInfo(list);


        Map<String, String> rangeCode = GetRangeCode(input.getSourceSampleNo());

        List<Predicate<LabMaininfo>> dynamicPredicates = new ArrayList<>();

        for (Map.Entry<String, String> itm : rangeCode.entrySet()) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getKey()) && p.getSeqNo() <= replaceLetter(itm.getValue()));
        }

        for (String itm : aimCode) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm) && p.getSeqNo() <= replaceLetter(itm));
        }

        List<LabMaininfo> list1 = list.stream().filter(t -> dynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.fail("没有要合并的数据");
        }

        /*待合并的结果数据、文件数据*/
        List<String> sampleNos = list1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
        LambdaQueryWrapper<LabRptresult> queryRptresultWrapper = new LambdaQueryWrapper<>();
        queryRptresultWrapper.eq(LabRptresult::getDelFlag, 0);
        queryRptresultWrapper.in(!sampleNos.isEmpty(), LabRptresult::getSampleNo, sampleNos);
        queryRptresultWrapper.eq(LabRptresult::getRptGroup, input.getSourceRptGroupId());

        Timestamp startTime1 = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime1 = Timestamp.valueOf(input.getSourceSampleda().substring(0, 10) + " 23:59:59");
        queryRptresultWrapper.ge(LabRptresult::getSampleda, startTime1);
        queryRptresultWrapper.le(LabRptresult::getSampleda, endTime1);


        if (!input.getItemDictCodes().isEmpty()) {
            queryRptresultWrapper.in(LabRptresult::getItemNo, input.getItemDictCodes());
        }
        List<LabRptresult> rptResultListSource = labRptresultMapper.selectList(queryRptresultWrapper);

        LambdaQueryWrapper<LabRptresultImage> queryRptresultImageWrapper = new LambdaQueryWrapper<>();
        queryRptresultImageWrapper.eq(LabRptresultImage::getDelFlag, 0);
        queryRptresultImageWrapper.in(!sampleNos.isEmpty(), LabRptresultImage::getSampleNo, sampleNos);
        queryRptresultImageWrapper.ge(LabRptresultImage::getSampleda, startTime1);
        queryRptresultImageWrapper.le(LabRptresultImage::getSampleda, endTime1);
        queryRptresultImageWrapper.eq(LabRptresultImage::getRptGroup, input.getSourceRptGroupId());
        List<LabRptresultImage> rptResultImageListSource = labRptresultImageMapper.selectList(queryRptresultImageWrapper);



        /*目标数据*/
        List<String> tAimCode = GetAimCode(input.getTargetSampleNo());
        LambdaQueryWrapper<LabMaininfo> tQueryWrapper = new LambdaQueryWrapper<>();
        tQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        tQueryWrapper.eq(LabMaininfo::getRptGroup, input.getTargetRptGroupId());

        Timestamp tStartTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 00:00:00");
        Timestamp tEndTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 23:59:59");
        tQueryWrapper.ge(LabMaininfo::getSampleda, tStartTime);
        tQueryWrapper.le(LabMaininfo::getSampleda, tEndTime);
        tQueryWrapper.in(!tAimCode.isEmpty(), LabMaininfo::getSampleNo, tAimCode);
        List<LabMaininfo> tList = labMaininfoMapper.selectList(tQueryWrapper);

        sortLabMainInfo(tList);

        Map<String, String> tRangeCode = GetRangeCode(input.getTargetSampleNo());

        List<Predicate<LabMaininfo>> tDynamicPredicates = new ArrayList<>();

        for (Map.Entry<String, String> itm : tRangeCode.entrySet()) {
            tDynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getKey()) && p.getSeqNo() <= replaceLetter(itm.getValue()));
        }

        for (String itm : tAimCode) {
            tDynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm) && p.getSeqNo() <= replaceLetter(itm));
        }

        List<LabMaininfo> tList1 = tList.stream().filter(t -> tDynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        /*是否一对多合并*/
        boolean OneToMany = false;

        List<String> SourceCodes = getCodeRangeList(input.getSourceSampleNo());//list1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());

        List<String> TargetCodes = null;//

        //非自动合并
        if (!BeanUtil.isEmpty(input.getAutoMerge()) && input.getAutoMerge() != 1) {
            TargetCodes = getCodeRangeList(input.getTargetSampleNo());//tList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());

            if (TargetCodes.isEmpty()) {
                return Result.fail("请选择合并后标本号范围");
            }
        } else {
            TargetCodes = new ArrayList<>();
        }

        //Source count = 1 时，为一对多模式//严格判断
        if (SourceCodes.toArray().length == 1 && TargetCodes.toArray().length > 1) {
            OneToMany = true;
            //1对多时,不能合并Wl
            input.setMergePatInfo(0);
        }

        //校验标本号范围是否一致
        if (!BeanUtil.isEmpty(input.getAutoMerge()) && !OneToMany && SourceCodes.size() != TargetCodes.size()) {
            return Result.fail("合并前标本号范围与合并后标本号范围不一致!");
        }

        if (!BeanUtil.isEmpty(input.getAutoMerge()) && input.getAutoMerge().equals(1)) {
            /*查询源病人信息*/
            List<String> patNos = list1.stream().map(LabMaininfo::getPatNo).collect(Collectors.toList());
            List<String> patNas = list1.stream().map(LabMaininfo::getPatNa).collect(Collectors.toList());

            /*查询目标病人信息*/
            tQueryWrapper = new LambdaQueryWrapper<>();
            tQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
            tQueryWrapper.eq(LabMaininfo::getRptGroup, input.getTargetRptGroupId());

            tStartTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 00:00:00");
            tEndTime = Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 23:59:59");
            tQueryWrapper.ge(LabMaininfo::getSampleda, tStartTime);
            tQueryWrapper.le(LabMaininfo::getSampleda, tEndTime);
            tQueryWrapper.in(LabMaininfo::getPatNo, patNos);
            tQueryWrapper.in(LabMaininfo::getPatNa, patNas);
            tList1 = labMaininfoMapper.selectList(tQueryWrapper);
            sortLabMainInfo(tList1);

            if (tList1.isEmpty()) {
                return Result.fail("未找到合并后病人信息");
            }
            //重新组织TargetCodes
            TargetCodes = new ArrayList<>();//tList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());

            for (LabMaininfo m : list1) {
                if (BeanUtil.isEmpty(m) || BeanUtil.isEmpty(m.getSampleNo()) || BeanUtil.isEmpty(m.getPatNo()) || BeanUtil.isEmpty(m.getPatNa())) {
                    continue;
                }
                int i = SourceCodes.indexOf(m.getSampleNo());
                List<LabMaininfo> tPats = tList.stream().filter(p -> p.getPatNo().equals(m.getPatNo()) && p.getPatNa().equals(m.getPatNa())).collect(Collectors.toList());

                if (tPats.isEmpty()) {
                    continue;
                }
                if (tPats.size() > 1) {
                    return Result.fail("合并前标本号" + m.getSampleNo() + "对应的病人信息重复,无法自动合并!");
                }
                if (i <= TargetCodes.toArray().length - 1 && BeanUtil.isEmpty(TargetCodes.get(i))) {
                    TargetCodes.set(i, tPats.get(0).getSampleNo());
                }
            }
        }

        /*准备待合并的目标检验结果*/
        List<String> tSampleNos = tList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
        LambdaQueryWrapper<LabRptresult> tResultQueryWrapper = new LambdaQueryWrapper<>();
        tResultQueryWrapper.eq(LabRptresult::getDelFlag, 0);
        tResultQueryWrapper.eq(LabRptresult::getRptGroup, input.getTargetRptGroupId());
        tResultQueryWrapper.ge(LabRptresult::getSampleda, tStartTime);
        tResultQueryWrapper.le(LabRptresult::getSampleda, tEndTime);
        tResultQueryWrapper.in(!tSampleNos.isEmpty(), LabRptresult::getSampleNo, tSampleNos);
        if (!input.getItemDictCodes().isEmpty()) {
            tResultQueryWrapper.in(LabRptresult::getItemNo, input.getItemDictCodes());
        }
        if (tSampleNos.isEmpty()) {
            tResultQueryWrapper.eq(LabRptresult::getMaininfoId, "!@#QWE!@#");
        }
        List<LabRptresult> tResultList = labRptresultMapper.selectList(tResultQueryWrapper);

        /*准备待合并的目标检验结果文件*/
        LambdaQueryWrapper<LabRptresultImage> tResultImageQueryWrapper = new LambdaQueryWrapper<>();
        tResultImageQueryWrapper.eq(LabRptresultImage::getDelFlag, 0);
        tResultImageQueryWrapper.eq(LabRptresultImage::getRptGroup, input.getTargetRptGroupId());
        tResultImageQueryWrapper.ge(LabRptresultImage::getSampleda, tStartTime);
        tResultImageQueryWrapper.le(LabRptresultImage::getSampleda, tEndTime);
        tResultImageQueryWrapper.in(!tSampleNos.isEmpty(), LabRptresultImage::getSampleNo, tSampleNos);
        if (tSampleNos.isEmpty()) {
            tResultImageQueryWrapper.eq(LabRptresultImage::getMaininfoId, "!@#QWE!@#");
        }
        List<LabRptresultImage> tResultImageList = labRptresultImageMapper.selectList(tResultImageQueryWrapper);


        /*验证是否够锁定、初审、审核*/
        List<LabMaininfo> validateList = tList1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());
        if (!validateList.isEmpty()) {
            return Result.fail("以下标本已锁定,无法合并!" + validateList.stream().map(LabMaininfo::getSampleNo).collect(Collectors.joining(",")));
        }
        List<LabMaininfo> validateList1 = tList1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().equals(new BigDecimal(1)) || p.getIsChk().equals(new BigDecimal(2)))).collect(Collectors.toList());
        if (!validateList1.isEmpty()) {
            return Result.fail("以下标本已初审或已审核,无法合并!" + validateList1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.joining(",")));
        }


        /*准备合并数据*/
        List<LabMaininfo> newMainInfoList = new ArrayList<>();
        List<LabRptresult> newRptResultList = new ArrayList<>();
        List<LabRptresultImage> newRptResultImageList = new ArrayList<>();

        List<LabMaininfo> overwriteMainInfoList = new ArrayList<>();
        List<LabRptresult> overwriteRptResultList = new ArrayList<>();
        List<LabRptresultImage> overwriteRptResultImageList = new ArrayList<>();

        List<LabMaininfo> deleteTMainInfoList = new ArrayList<>();
        List<LabRptresult> deleteTRptResultList = new ArrayList<>();
        List<LabRptresultImage> deleteTRptResultImageList = new ArrayList<>();

        int oneToManyCount = 0;
        for (int i = 0; i < list1.size(); i++) {
            LabMaininfo sw;
            int sIndex = 0;
            if (OneToMany) {
                if (oneToManyCount >= TargetCodes.size()) {
                    break;
                }
                i = 0;
                sw = list1.get(0);
                sIndex = oneToManyCount;

                oneToManyCount += 1;
            } else {
                sw = list1.get(i);
                String sSampleNo = sw.getSampleNo();
                sIndex = SourceCodes.indexOf(sSampleNo);
            }
            //得到目标标本号
            String tCode = TargetCodes.get(sIndex);

            //自动合并合并未找到目标Code时，不继续
            if (!BeanUtil.isEmpty(input.getAutoMerge()) && input.getAutoMerge().equals(1) && BeanUtil.isEmpty(tCode)) {
                continue;
            }

            List<LabMaininfo> tmis = tList1.stream().filter(p -> p.getSampleNo().equals(tCode)).collect(Collectors.toList());
            LabMaininfo tmiFirst = tmis.isEmpty() ? null : tmis.get(0);

            LabMaininfo _miEntry = new LabMaininfo();
            if (!BeanUtil.isEmpty(tmiFirst)) {
                BeanUtil.copyProperties(tmiFirst, _miEntry);
                /*1：覆盖，0如果存在就取消*/
                if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(1)) {
                    BeanUtil.copyProperties(sw, _miEntry, "id");
                    _miEntry.setSampleda(tmiFirst.getSampleda());
                    _miEntry.setRptGroup(tmiFirst.getRptGroup());
                    _miEntry.setSampleNo(tmiFirst.getSampleNo());
                    _miEntry.setCreateTime(tmiFirst.getCreateTime());
                }
                _miEntry.setReqNo(sw.getReqNo());
                _miEntry.setSampleType(sw.getSampleType());
                _miEntry.setQuantity(sw.getQuantity());
                _miEntry.setIsChk(new BigDecimal(0));
                _miEntry.setTestDoctor("");
                _miEntry.setChkDoctor("");
                _miEntry.setChkTime(null);
                _miEntry.setTestTime(null);
                _miEntry.setIsPrint(0);
                _miEntry.setPrintDoctor("");
                _miEntry.setPrintTime(null);
                _miEntry.setPrintCount(new BigDecimal(0));
                _miEntry.setIsLock(0);
                _miEntry.setIsAutoPrint(0);
                _miEntry.setAutoPrintTime(null);
                if (BeanUtil.isEmpty(input.getMergePatInfo()) || !input.getMergePatInfo().equals(1)) {
                    /*不合并病人信息*/
                    _miEntry.setReqNo("");
                    _miEntry.setPatType("");
                    _miEntry.setPatNa("");
                    _miEntry.setPatNo("");
                    _miEntry.setPatPyName("");
                    _miEntry.setSex("");
                    _miEntry.setAge(null);
                    _miEntry.setAgeUnit("");
                    _miEntry.setSecAge(null);
                    _miEntry.setSecAgeUnit("");
                    _miEntry.setIdNo(null);
                }
                /*合并检验医师*/
                if (!BeanUtil.isEmpty(input.getMergeTestDoctor()) && input.getMergeTestDoctor().equals(1)) {
                    _miEntry.setChkDoctor(sw.getChkDoctor());
                    _miEntry.setTestDoctor(sw.getTestDoctor());
                }
                overwriteMainInfoList.add(_miEntry);
            } else {
                /*生成新数据*/
                BeanUtil.copyProperties(sw, _miEntry, "id");
                _miEntry.setSampleda(Timestamp.valueOf(input.getTargetSampleda().substring(0, 10) + " 00:00:00"));
                _miEntry.setRptGroup(input.getTargetRptGroupId());
                _miEntry.setSampleNo(tCode);
                _miEntry.setIsChk(new BigDecimal(0));
                _miEntry.setTestDoctor(null);
                _miEntry.setChkDoctor(null);
                _miEntry.setChkTime(null);
                _miEntry.setTestTime(null);
                _miEntry.setIsPrint(0);
                _miEntry.setPrintDoctor(null);
                _miEntry.setPrintTime(null);
                _miEntry.setPrintCount(new BigDecimal(0));
                _miEntry.setIsLock(0);
                _miEntry.setIsAutoPrint(0);
                _miEntry.setAutoPrintTime(null);
                if (BeanUtil.isEmpty(input.getMergePatInfo()) || !input.getMergePatInfo().equals(1)) {
                    /*不合并病人信息*/
                    _miEntry.setReqNo(null);
                    _miEntry.setPatType(null);
                    _miEntry.setPatNa(null);
                    _miEntry.setPatNo(null);
                    _miEntry.setPatPyName(null);
                    _miEntry.setSex(null);
                    _miEntry.setAge(null);
                    _miEntry.setAgeUnit(null);
                    _miEntry.setSecAge(null);
                    _miEntry.setSecAgeUnit(null);
                    _miEntry.setIdNo(null);
                }

                if (!BeanUtil.isEmpty(input.getMergeTestDoctor()) && input.getMergeTestDoctor().equals(1)) {
                    _miEntry.setChkDoctor(sw.getChkDoctor());
                    _miEntry.setTestDoctor(sw.getTestDoctor());
                }
                newMainInfoList.add(_miEntry);
            }

            /*移动时需要删除源数据*/
            if (ToolsUtils.isNotEmpty(input.getCopy()) && input.getCopy().equals(0)) {
                if (ToolsUtils.isNotEmpty(input.getIsOneItemDict()) && input.getIsOneItemDict().equals(1)) {
                    //按单个项目时 不删除
                } else {
                    sw.setDelFlag(1);
                    deleteTMainInfoList.add(sw);
                }
            }

            /*待合并结果处理*/
            if ((ToolsUtils.isNotEmpty(input.getIsAllItemDict()) && input.getIsAllItemDict().equals(1)) || (ToolsUtils.isNotEmpty(input.getIsOneItemDict()) && input.getIsOneItemDict().equals(1))) {
                List<LabRptresult> _srptrList = rptResultListSource.stream().filter(p -> p.getSampleNo().equals(sw.getSampleNo()) && p.getRptGroup().equals(sw.getRptGroup())).collect(Collectors.toList());//p.getMaininfoId().equals(sw.getId())
                for (LabRptresult srptritm : _srptrList) {
                    LabRptresult _rptEntry = new LabRptresult();
                    LabRptresult _rptEntryTemp = new LabRptresult();
                    /*按项目代号合并 0否  1是*/
                    if (!BeanUtil.isEmpty(input.getMergeByItemNo()) && input.getMergeByItemNo().equals(1)) {
                        String itemNo = srptritm.getItemNo();

                        List<LabRptresult> _rptResultAimItems = tResultList.stream().filter(p -> p.getItemNo().equals(itemNo) && p.getSampleNo().equals(tCode)).collect(Collectors.toList());
                        if (!_rptResultAimItems.isEmpty()) {
                            BeanUtil.copyProperties(_rptResultAimItems.get(0), _rptEntry);
                        }

                        BeanUtil.copyProperties(srptritm, _rptEntryTemp, "id");
                    } else {
                        String itemNo = srptritm.getItemNo();

                        List<LabRptresult> _rptResultAimItems = tResultList.stream().filter(p -> p.getItemNo().equals(itemNo) && p.getSampleNo().equals(tCode)).collect(Collectors.toList());
                        if (!_rptResultAimItems.isEmpty()) {
                            BeanUtil.copyProperties(_rptResultAimItems.get(0), _rptEntry);
                        }

                        BeanUtil.copyProperties(srptritm, _rptEntryTemp, "id");
                    }

                    if (StringUtils.isBlank(_miEntry.getId())) {
                        // 获取UUID的前19位作为ASSIGN_ID
                        String assignId = IdUtil.getSnowflake().nextId() + "";
                        _miEntry.setId(assignId);
                    }

                    _rptEntryTemp.setMaininfoId(_miEntry.getId());
                    _rptEntryTemp.setSampleda(_miEntry.getSampleda());
                    _rptEntryTemp.setRptGroup(_miEntry.getRptGroup());
                    _rptEntryTemp.setSampleNo(_miEntry.getSampleNo());

                    if (BeanUtil.isEmpty(_rptEntry) || StringUtils.isBlank(_rptEntry.getId())) {
                        newRptResultList.add(_rptEntryTemp);
                    } else {
                        /*如果存在就取消*/
                        if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(0)) {
                            continue;
                        }
                        /*如果存在就覆盖*/
                        if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(1)) {
                            BeanUtil.copyProperties(_rptEntryTemp, _rptEntry, "id");
                            _rptEntry.setMaininfoId(_miEntry.getId());
                            _rptEntry.setSampleda(_miEntry.getSampleda());
                            _rptEntry.setRptGroup(_miEntry.getRptGroup());
                            _rptEntry.setSampleNo(_miEntry.getSampleNo());
                            overwriteRptResultList.add(_rptEntry);
                        }
                        /*移动时 需要删除源中的项目*/
                        if (ToolsUtils.isNotEmpty(input.getCopy()) && input.getCopy().equals(0)) {
                            if (ToolsUtils.isNotEmpty(input.getIsOneItemDict()) && input.getIsOneItemDict().equals(1)) {
                                if (ToolsUtils.isNotEmpty(input.getItemNo()) && input.getItemNo().equals(srptritm.getItemNo())) {
                                    srptritm.setDelFlag(1);
                                    deleteTRptResultList.add(srptritm);
                                }
                            } else {
                                srptritm.setDelFlag(1);
                                deleteTRptResultList.add(srptritm);
                            }
                        }
                    }
                }
            }
            /*待合并结果文件处理,只有选择合并文件采取处理图片*/
            if (ToolsUtils.isNotEmpty(input.getMergeFile()) && input.getMergeFile().equals(1)) {
                List<LabRptresultImage> _srptrimageList = rptResultImageListSource.stream().filter(p -> p.getSampleNo().equals(sw.getSampleNo()) && p.getRptGroup().equals(sw.getRptGroup())).collect(Collectors.toList());
                for (LabRptresultImage swrf : _srptrimageList) {
                    List<LabRptresultImage> _entries = tResultImageList.stream().filter(p -> p.getImageName().equals(swrf.getImageName()) && p.getSampleNo().equals(tCode)).collect(Collectors.toList());

                    LabRptresultImage _entry = new LabRptresultImage();
                    BeanUtil.copyProperties(swrf, _entry, "id");
                    if (StringUtils.isBlank(_miEntry.getId())) {
                        String assignId = IdUtil.getSnowflake().nextId() + "";
                        _miEntry.setId(assignId);
                    }
                    _entry.setMaininfoId(_miEntry.getId());
                    _entry.setSampleda(_miEntry.getSampleda());
                    _entry.setRptGroup(_miEntry.getRptGroup());
                    _entry.setSampleNo(_miEntry.getSampleNo());
                    if (_entries.isEmpty()) {
                        newRptResultImageList.add(_entry);
                    } else {
                        LabRptresultImage existEntry = _entries.get(0);

                        /*已有该图片情况下*/
                        /*如果存在就取消*/
                        if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(0)) {
                            continue;
                        }

                        /*如果存在就覆盖*/
                        if (!BeanUtil.isEmpty(input.getOverwrite()) && input.getOverwrite().equals(1)) {
                            BeanUtil.copyProperties(swrf, existEntry, "id");
                            existEntry.setMaininfoId(_miEntry.getId());
                            existEntry.setSampleda(_miEntry.getSampleda());
                            existEntry.setRptGroup(_miEntry.getRptGroup());
                            existEntry.setSampleNo(_miEntry.getSampleNo());
                            overwriteRptResultImageList.add(existEntry);
                        }

                        /*移动时 需要删除源中的项目*/
                        if (ToolsUtils.isNotEmpty(input.getCopy()) && input.getCopy().equals(0)) {
                            swrf.setDelFlag(1);
                            deleteTRptResultImageList.add(swrf);
                        }
                    }
                }
            }

            if (OneToMany) {
                i = -1;
            }

        }

        //保存数据
        //插入新生成的数据
        if (!newMainInfoList.isEmpty()) {
            boolean ires1 = labMaininfoService.saveBatch(newMainInfoList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }

            new Thread(() -> {
                for (LabMaininfo m : newMainInfoList) {
                    //上机之后插入状态信息
                    LabMainState reqState1 = new LabMainState();
                    reqState1.setMaininfoId(m.getId());
                    reqState1.setStateCode("90");
                    reqState1.setStateValue("标本合并创建检验记录");
                    labMainStateService.save(reqState1);
                }
            }).start();
        }

        if (!overwriteMainInfoList.isEmpty()) {
            boolean ires1 = labMaininfoService.updateBatchById(overwriteMainInfoList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!deleteTMainInfoList.isEmpty()) {
            boolean ires1 = labMaininfoService.removeByIds(deleteTMainInfoList.stream().map(LabMaininfo::getId).collect(Collectors.toList()));
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!newRptResultList.isEmpty()) {
            boolean ires1 = labRptresultService.saveBatch(newRptResultList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!overwriteRptResultList.isEmpty()) {
            boolean ires1 = labRptresultService.updateBatchById(overwriteRptResultList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!deleteTRptResultList.isEmpty()) {
            //boolean ires1 = labRptresultService.updateBatchById(deleteTRptResultList);
            boolean ires1 = labRptresultService.removeByIds(deleteTRptResultList.stream().map(LabRptresult::getId).collect(Collectors.toList()));
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!newRptResultImageList.isEmpty()) {
            boolean ires1 = labRptresultImageService.saveBatch(newRptResultImageList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!overwriteRptResultImageList.isEmpty()) {
            boolean ires1 = labRptresultImageService.updateBatchById(overwriteRptResultImageList);
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        if (!deleteTRptResultImageList.isEmpty()) {
            boolean ires1 = labRptresultImageService.removeByIds(deleteTRptResultImageList.stream().map(LabRptresultImage::getId).collect(Collectors.toList()));
            if (!ires1) {
                return Result.fail("合并检验记录失败,请联系管理员");
            }
        }

        /*合并完成后，重新计算参开范围*/
        try {
            for (LabMaininfo m : newMainInfoList) {
                /*重新计算检验结果*/
                labRptresultService.reCalcRptRssults(m);
            }

            for (LabMaininfo m : overwriteMainInfoList) {
                /*重新计算检验结果*/
                labRptresultService.reCalcRptRssults(m);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.succ(1, "合并成功", null);
    }

    public void sortLabMainInfo(List<LabMaininfo> maininfos) {
        for (LabMaininfo item : maininfos) {
            try {
                if (!BeanUtil.isEmpty(item.getSampleNo())) {
                    String a = item.getSampleNo();
                    for (Map.Entry<String, Integer> m : SortMappers.SORT_CONSTANT_MAP.entrySet()) {
                        if (item.getSampleNo().contains(m.getKey())) {
                            a = a.replace(m.getKey(), m.getValue().toString());
                        }
                    }
                    item.setSeqNo(StringUtils.isEmpty(a) ? 999999999 : Integer.parseInt(a));
                }
            } catch (NumberFormatException e) {
                item.setSeqNo(999999999);
            }
        }
    }

    /*获取单个标本号*/
    private List<String> GetAimCode(String code) {
        List<String> codes = new ArrayList<>();

        code = code.replace("，", ",");
        code = code.replace("—", "-");

        String[] codeArray = code.split(",");

        for (String c : codeArray) {
            if (!c.contains("-")) {
                codes.add(c);
            } else {
                String[] arr = code.split("-");
                for (int i = Integer.parseInt(arr[0]); i <= Integer.parseInt(arr[1]); i++) {
                    codes.add(i + "");
                }
            }
        }
        return codes;
    }

    /*获取范围标本号*/
    private Map<String, String> GetRangeCode(String code) {
        Map<String, String> codes = new HashMap<>();
        code = code.replace("，", ",");
        code = code.replace("—", "-");

        String[] codeArray = code.split(",");

        for (String c : codeArray) {
            if (c.contains("-")) {
                int count = 0;
                int len = 0;
                String[] range = c.split("-");
                //仅开始结束号码长度相同时前面补0
                if (range[0].length() == range[1].length()) {
                    len = range[0].length();
                }
                String codeMin = BeanUtil.isEmpty(range[0]) ? "" : range[0];
                String codeMax = BeanUtil.isEmpty(range[1]) ? "" : range[1];

                codes.put(codeMin, codeMax);
            }
        }
        return codes;
    }

    private static String codeAutoIncrement(String minCode) {
        char[] charArr = minCode.toCharArray();
        String str = "";
        for (int i = charArr.length - 1; i >= 0; i--) {
            if (Character.isDigit(charArr[i])) {
                str = charArr[i] + str;
            } else {
                break;
            }
        }
        int curInt = Integer.parseInt(str);
        String _str = String.valueOf(curInt + 1);
        if (_str.length() < minCode.length()) {
            _str = minCode.substring(0, minCode.length() - str.length()) + _str;
        }
        return _str;
    }

    private static List<String> getCodeRangeList(String code) {
        List<String> codes = new ArrayList<>();
        int sortCodeLen = 20;
        code = code.replace("，", ",");
        code = code.replace("—", "-");
        String[] codeArray = code.split(",");
        for (String c : codeArray) {
            if (c.contains("-")) {
                int count = 0;
                int len = 0;
                String[] range = c.split("-");

                if (range[0].length() == range[1].length()) {
                    len = range[0].length();
                }
                String codeMin = range[0];
                String codeMax = range[1];

                String currentCode = codeMin;

                codes.add(range[0]);
                do {
                    currentCode = codeAutoIncrement(currentCode);//codeAutoIncrement(currentCode).substring(sortCodeLen);
                    codes.add(currentCode);
                    count += 1;

                    if (count > 10000) {
                        break;
                    }

                } while (!currentCode.equalsIgnoreCase(codeMax));

            } else {
                codes.add(c);
            }
        }

        return codes;
    }

    public Integer replaceLetter(String keyValue) {
        Integer k = -1;
        try {
            for (Map.Entry<String, Integer> m : SortMappers.SORT_CONSTANT_MAP.entrySet()) {
                if (keyValue.contains(m.getKey())) {
                    keyValue = keyValue.replace(m.getKey(), m.getValue().toString());
                }
            }
            k = Integer.parseInt(keyValue);
        } catch (Exception exception) {
            k = 999999999;
        }
        return k;
    }


    public void specialLabRptHandleold(List<PubReportRules> reportRules, List<LabRptresult> rptresultList, List<ReportPreviewDto> reportPreviewDtos, LabMaininfo labMaininfo) {
        //查询出申请详情用于特殊报告判断
        List<LabReqdetailDel> labReqdetailDels = labReqdetailDelService.list(//防止格式化
                new LambdaQueryWrapper<LabReqdetailDel>()//防止格式化
                        .eq(LabReqdetailDel::getReqNo, labMaininfo.getReqNo())//防止格式化
                        .eq(LabReqdetailDel::getDelFlag, 0));
        //提取特殊报告模板，并从reportRules中移除特殊报告
        List<PubReportRules> reportRulesRuleType5s = new ArrayList<>();//特殊报告
        for (PubReportRules pubReportRules : reportRules) {
            if ("5".equals(pubReportRules.getRuleType())) {
                reportRulesRuleType5s.add(pubReportRules);
            }
        }
        //循环reportRulesRuleType5s,判断是否符合要求后加入reportPreviewDtos
        for (PubReportRules pubReportRules : reportRulesRuleType5s) {
            //从reportRules中删除特殊报告模板，避免重复判断
            reportRules.remove(pubReportRules);
            if ("0".equals(pubReportRules.getIsUse())) {
                continue;
            }
            //rptresultList循环，逐报告项目判断是否满足条件
            for (LabRptresult rptresult : rptresultList) {
                String sql = "select count(1) as result from dual where 1=1 ";
                String afterReplace = new CalcItemFormulaReplcae().ReplaceCondition(pubReportRules.getRules().toLowerCase(), labMaininfo, rptresult);
                if (!StringUtils.isEmpty(afterReplace)) {
                    sql += " and " + afterReplace;
                }
                logger.info("sql:" + sql);
                try {
                    List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sql);
                    // 遍历 List 中的每个 Map
                    String ResValue = "";
                    for (Map<String, Object> map : calcResult) {
                        // 遍历 Map 中的键值对
                        for (Map.Entry<String, Object> entry : map.entrySet()) {
                            String key = entry.getKey();
                            Object value = entry.getValue();
                            ResValue = value.toString();
                        }
                    }
                    //只要有一个检验项目满足则记录到reportPreviewDtos,不再继续其他检验项目判断
                    //此处逻辑有可能不健全，待优化
                    if (!StringUtils.isEmpty(ResValue) && ResValue.equals("1")) {
                        ReportPreviewDto reportPreviewDto = new ReportPreviewDto();
                        reportPreviewDto.setId(labMaininfo.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setReportId(pubReportRules.getReportId());
                        reportPreviewDto.setReportTemplateName(pubReportRules.getReportName());
                        //判断reportPreviewDtos是否包含reportPreviewDto，则不加入
//                        if (reportPreviewDtos.contains(reportPreviewDto)){
//                            break;
//                        }
                        reportPreviewDtos.add(reportPreviewDto);
                        return;
                        //break;
                    }
                } catch (Exception e) {

                }
            }
        }
    }


    public void specialLabRptHandle(List<PubReportRules> reportRules, List<LabRptresult> rptresultList, List<ReportPreviewDto> reportPreviewDtos, LabMaininfo labMaininfo) {
        //提取特殊报告模板，并从reportRules中移除特殊报告
        List<PubReportRules> reportRulesRuleType5s = new ArrayList<>();//特殊报告
        for (PubReportRules pubReportRules : reportRules) {
            if ("5".equals(pubReportRules.getRuleType())) {
                if (StringUtils.isNotEmpty(pubReportRules.getRules()) && pubReportRules.getRules().length() > 0) {
                    reportRulesRuleType5s.add(pubReportRules);
                }
            }
//            reportRulesRuleType5s.add(pubReportRules);
        }
        //查询出申请详情用于特殊报告判断
        List<LabReqdetailDel> labReqdetailDels = labReqdetailDelService.list(//防止格式化
                new LambdaQueryWrapper<LabReqdetailDel>()//防止格式化
                        .eq(LabReqdetailDel::getReqNo, labMaininfo.getReqNo())//防止格式化
                        .eq(LabReqdetailDel::getDelFlag, 0));
        //循环reportRulesRuleType5s,判断是否符合要求后加入reportPreviewDtos
        for (PubReportRules pubReportRules : reportRulesRuleType5s) {
            //从reportRules中删除特殊报告模板，避免重复判断
            reportRules.remove(pubReportRules);
            if ("0".equals(pubReportRules.getIsUse())) {
                continue;
            }
            /** 最终形态
             * select count(1) as result from dual where exists (
             * 	select 1
             * 	from
             * 	(
             * 		(
             * 		select '1' as codename
             * 		union
             * 		select '2' as codename
             * 		union
             * 		select '3' as codename
             * 		)
             * 	) t1
             * 	where t1.id in  ('2','3')
             * 	)
             * **/
            StringBuilder sqlwhere = new StringBuilder(" select count(1) as result from dual where exists (select 1 from (");

            List<StringBuilder> list = new ArrayList<>();
            //labReqdetailDels循环，住报告项目判断是否满足条件
            for (LabReqdetailDel labReqdetailDel : labReqdetailDels) {
                for (LabRptresult rptresult : rptresultList) {
                    StringBuilder sqlfield = new StringBuilder(" select ");
                    //开始拼接sql
                    //region 第一步拼接字段
                    sqlfield.append("'").append(labMaininfo.getOrgId()).append("' as ORGID , ");
                    //申请科室
                    sqlfield.append("'").append(labMaininfo.getReqDept()).append("' as DPTID ,");
                    //申请病区
                    sqlfield.append("'").append(labMaininfo.getReqWard()).append("' as REQWARD , ");

                    //病人来源
                    sqlfield.append("'").append(labMaininfo.getPatType()).append("' as PATTYPE , ");

                    //采样类型
                    sqlfield.append("'").append(labMaininfo.getSampleType()).append("' as SAMPLETYPE , ");

                    //条码号
                    sqlfield.append("'").append(labMaininfo.getReqNo()).append("' as REQNO , ");

                    //性别
                    sqlfield.append("'").append(labMaininfo.getSex()).append("' as SEX , ");

                    //年龄
                    sqlfield.append("'").append(labMaininfo.getAge()).append("' as AGE , ");

                    //2023-02-17添加,妊娠,采样部位体位等
                    sqlfield.append("'").append(labMaininfo.getPhyCycel()).append("' as MENSTRUALCYCLE , ");

                    //生理周期
                    sqlfield.append("'").append(labMaininfo.getLactation()).append("' as ISINLACTATION , ");

                    //妊娠期
                    sqlfield.append("'").append(labMaininfo.getGestation()).append("' as GESTATION , ");

                    //孕周
                    sqlfield.append("'").append(labMaininfo.getGestationWeek()).append("' as GESTATIONWEEK , ");

                    //孕次
                    sqlfield.append("'").append(labMaininfo.getGestationTimes()).append("' as GESTATIONTIMES , ");

                    //诊断
                    sqlfield.append("'").append(labMaininfo.getDiagnose()).append("' as DIAGNOSE , ");

                    //将字段feeCode写入字符串中
                    sqlfield.append("'").append(labReqdetailDel.getFeeCode()).append("' as FEEID , ");

                    sqlfield.append("'").append(labReqdetailDel.getFeeName()).append("' as FEENAME , ");
                    sqlfield.append("'").append(rptresult.getItemNo()).append("' as ITEMNO , ");

                    sqlfield.append("'").append(rptresult.getTestResult()).append("' as TESTRESULT  ");
                    list.add(sqlfield);

                }

            }
            String query = String.join(" UNION ", list);
            sqlwhere.append(query);


            // endregion不为空时开始第二步
            //声明一个字符串数组
            String[] values = {"DPTID", "sex", "SEX", "age", "AGE", "sampletype", "SAMPLETYPE", "feeid", "FEEID", "MENSTRUALCYCLE", "reqNo", "reqno",
                    "pattype", "PATTYPE", "itemno"};

            //region第二步拼接查询
            List<String> newRules = new ArrayList<>();
            List<String> queryRules = new ArrayList<>();
            String rules = pubReportRules.getRules();
            String[] andRules = rules.split("and");
            for (String andRule : andRules) {
                if (andRule.contains("notexists")) {
                    //循环values
                    for (String value : values) {
                        if (andRule.contains(value)) {
                            newRules.add(" NOT EXISTS (SELECT 1 FROM PUB_PEPORT_RULES_EXIST WHERE FIELD_CODE ='" + value + "' AND RULE_ID ='" + pubReportRules.getId() + "' AND t1." + value + "=FIELD_VALUE) ");
                        }
                    }
                } else if (andRule.contains("exists")) {
                    //循环values
                    for (String value : values) {
                        if (andRule.contains(value)) {
                            newRules.add(" EXISTS (SELECT 1 FROM PUB_PEPORT_RULES_EXIST WHERE FIELD_CODE ='" + value + "' AND RULE_ID ='" + pubReportRules.getId() + "' AND t1." + value + "=FIELD_VALUE) ");
                        }
                    }
                } else {
                    queryRules.add(andRule);
                }
            }
            String newQuery = String.join("and", newRules);
            String andQuery = String.join("and", queryRules);
            String afterReplace = new CalcItemFormulaReplcae().ReplaceConditionWhere(andQuery.toUpperCase());
            //加入拼接的字段去除最后面的union
            //sqlwhere.append(query.substring(0, query.length() - 6));
            sqlwhere.append(") t1 where 1=1 ");
            if (StringUtils.isNotBlank(newQuery)) {
                sqlwhere.append(" and " + newQuery);
            }
            if (StringUtils.isNotBlank(afterReplace)) {
                sqlwhere.append(" and " + afterReplace);
            }
            sqlwhere.append(")");
            // endregion
            logger.info("sql:" + sqlwhere);
            try {
                List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sqlwhere.toString());
                // 遍历 List 中的每个 Map
                String ResValue = "";
                for (Map<String, Object> map : calcResult) {
                    // 遍历 Map 中的键值对
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        ResValue = value.toString();
                    }
                }
                //只要有一个检验项目满足则记录到reportPreviewDtos,不再继续其他检验项目判断
                if (!StringUtils.isEmpty(ResValue) && ResValue.equals("1")) {
                    ReportPreviewDto reportPreviewDto = new ReportPreviewDto();
                    reportPreviewDto.setIsChecked(true);
                    reportPreviewDto.setReportId(pubReportRules.getReportId());
                    reportPreviewDto.setReportTemplateName(pubReportRules.getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                    logger.info("reportId:" + pubReportRules.getReportId());
                    logger.info("reportTemplateName:" + pubReportRules.getReportName());
                    return;
                }
            } catch (Exception e) {

            }
        }
    }

    /*扫码上机验证*/
    public Result validateByScanReqNo(LabMaininfo labMaininfo) {
        if (ToolsUtils.isEmpty(labMaininfo.getReqNo())) {
            return Result.succ(1, "条码号为空不做验证", true);
        }
        if (ToolsUtils.isEmpty(labMaininfo.getRptGroup())) {
            return Result.succ(1, "报告单元为空不做验证", true);
        }
        Long st = System.currentTimeMillis();
        /*查询申请*/
        LambdaQueryWrapper<LabReqMain> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabReqMain::getDelFlag, 0);
        wrapper.eq(LabReqMain::getReqNo, labMaininfo.getReqNo());
        List<LabReqMain> rmList = labReqMainMapper.selectList(wrapper);
        if (ToolsUtils.isEmpty(rmList)) {
            Long st5 = System.currentTimeMillis();
            System.out.println("调优==========》验证报告单元条码乱【5】扫总共耗时：" + (st5 - st) + "ms");
            return Result.succ(1, "申请单不存在", true);/*申请不存在，无需验证*/
        }

        /*条码必须包含当前报告单元的收费项目【报告单元系统选项】*/
        SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(labMaininfo.getOrgId(), "tmbxbhdqbgdysfxm", labMaininfo.getRptGroup(), null);
        String valueKey = ToolsUtils.isEmpty(paramResult) ? "" : paramResult.getValueStr();

        String barcodeNo = rmList.get(0).getBarCode();
        if (ToolsUtils.isEmpty(barcodeNo) && (ToolsUtils.isEmpty(valueKey) || !"1".equals(valueKey))) {
            Long st4 = System.currentTimeMillis();
            System.out.println("调优==========》验证报告单元条码乱【4】扫总共耗时：" + (st4 - st) + "ms");
            return Result.succ(1, "分管类别编号为空不做验证", true);
        }

        /*查询报告单元-分管类别对照*/
        LambdaQueryWrapper<LabRptVsBarcode> rptGroupWrapper = new LambdaQueryWrapper<>();
        rptGroupWrapper.eq(LabRptVsBarcode::getDelFlag, 0);
        rptGroupWrapper.eq(LabRptVsBarcode::getRptGroup, labMaininfo.getRptGroup());
        rptGroupWrapper.eq(LabRptVsBarcode::getBarcodeNo, barcodeNo);
        List<LabRptVsBarcode> rptGroupList = labRptVsBarcodeMapper.selectList(rptGroupWrapper);


        if (ToolsUtils.isEmpty(rptGroupList) && ToolsUtils.isNotEmpty(valueKey) && "1".equals(valueKey)) {
            Long st2 = System.currentTimeMillis();
            System.out.println("调优==========》验证报告单元条码乱【2】扫总共耗时总共耗时：" + (st2 - st) + "ms");
            return Result.succ(1, "该条码没有本仪器可用的项目,禁止上机", false);
        }
        Long st3 = System.currentTimeMillis();
        System.out.println("调优==========》验证报告单元条码乱【3】扫总共耗时：" + (st3 - st) + "ms");
        return Result.succ(0, "无验证", true);
    }

    /*查询上机记录*/
    public LabMaininfo getLabMaininfoById(String Id) {
        long st = System.currentTimeMillis();
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getSeq, LabMaininfo::getRptGroupSeq);
        queryWrapper.leftJoin(LabSampleType.class, p->p.eq(LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType).eq(LabSampleType::getDelFlag, 0));
        queryWrapper.leftJoin(SysOrgDepartment.class, p->p.eq(SysOrgDepartment::getCode, LabMaininfo::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", p->p.eq(SysUser::getUsername, LabMaininfo::getTestDoctor).eq(SysUser::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "chk", p->p.eq(SysUser::getUsername, LabMaininfo::getChkDoctor).eq(SysUser::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "rechk", p->p.eq(SysUser::getUsername, LabMaininfo::getReChkDoctor).eq(SysUser::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "prt", p->p.eq(SysUser::getUsername, LabMaininfo::getPrintDoctor).eq(SysUser::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "sampl", p->p.eq(SysUser::getUsername, LabMaininfo::getSamplingDoctor).eq(SysUser::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "signer", p->p.eq(SysUser::getUsername, LabMaininfo::getSignerDoctor).eq(SysUser::getDelFlag, 0));
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", p->p.eq(LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabRptGroup::getDelFlag, 0));

        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getId, Id);

        LabMaininfo labMaininfos = labMaininfoMapper.selectOne(queryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : Arrays.asList(labMaininfos)) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));

            }
        }
        long st2 = System.currentTimeMillis();
        System.out.println("调优==========》查询上机记录总共耗时：" + (st2 - st) + "ms");
        return labMaininfos;
    }

}
